(() => {
  const state = {
    currentTool: "pencil",
    selectionMode: "select",
  };

  const body = document.body;
  const selectionModeToggle = document.getElementById("selectionModeToggle");
  const paletteWindow = document.getElementById("paletteWindow");
  const exportWindow = document.getElementById("exportWindow");
  const sheetOverlay = document.getElementById("sheetOverlay");
  const deviceLabel = document.getElementById("deviceLabel");
  const drawers = Array.from(document.querySelectorAll(".drawer"));
  const sheets = Array.from(document.querySelectorAll(".sheet"));

  function setDeviceMode() {
    const mode = window.innerWidth >= 900 ? "tablet" : "phone";
    body.classList.remove("device-phone", "device-tablet");
    body.classList.add(`device-${mode}`);
    if (deviceLabel) {
      deviceLabel.textContent =
        mode === "tablet" ? "平板端 · 全功能布局" : "手机端 · 自适应布局";
    }
  }

  function closeDrawers() {
    drawers.forEach((drawer) => drawer.classList.remove("is-active"));
  }

  function toggleDrawer(target) {
    const drawer = document.querySelector(`[data-drawer="${target}"]`);
    if (!drawer) return;
    const isActive = drawer.classList.contains("is-active");
    closeDrawers();
    closeSheets();
    if (!isActive) {
      drawer.classList.add("is-active");
    }
  }

  function closeSheets() {
    if (!sheetOverlay) return;
    sheetOverlay.classList.remove("is-active");
    sheets.forEach((sheet) => {
      sheet.hidden = true;
      sheet.classList.remove("is-active");
    });
    if (exportWindow) {
      exportWindow.setAttribute("aria-hidden", "true");
    }
  }

  function openSheet(name) {
    if (name === "export") {
      openExportWindow();
      return;
    }
    const sheet = sheets.find((s) => s.dataset.sheet === name);
    if (!sheet || !sheetOverlay) return;
    sheets.forEach((s) => {
      const isTarget = s === sheet;
      s.hidden = !isTarget;
      s.classList.toggle("is-active", isTarget);
    });
    sheetOverlay.classList.add("is-active");
  }

  function togglePalette() {
    if (!paletteWindow) return;
    const nextState = !paletteWindow.classList.contains("is-active");
    paletteWindow.classList.toggle("is-active", nextState);
    if (nextState) {
      closeDrawers();
      closeSheets();
    }
  }

  function closeFloating() {
    closeDrawers();
    closeSheets();
    if (paletteWindow) {
      paletteWindow.classList.remove("is-active");
    }
  }

  function setTool(tool) {
    state.currentTool = tool;
    document.querySelectorAll("[data-tool]").forEach((btn) => {
      btn.classList.toggle(
        "is-active",
        btn.getAttribute("data-tool") === state.currentTool
      );
    });
    if (selectionModeToggle) {
      selectionModeToggle.classList.toggle(
        "is-hidden",
        state.currentTool !== "selection"
      );
    }
  }

  function bindTools() {
    document.querySelectorAll("[data-tool]").forEach((btn) => {
      btn.addEventListener("click", () => {
        setTool(btn.getAttribute("data-tool"));
      });
    });

    document
      .querySelectorAll("#selectionModeToggle .selection-chip")
      .forEach((btn) => {
        btn.addEventListener("click", () => {
          document
            .querySelectorAll("#selectionModeToggle .selection-chip")
            .forEach((b) => b.classList.remove("is-active"));
          btn.classList.add("is-active");
          state.selectionMode = btn.getAttribute("data-mode");
        });
      });
  }

  function bindDrawers() {
    document.querySelectorAll("[data-drawer-target]").forEach((btn) => {
      btn.addEventListener("click", () => {
        const target = btn.getAttribute("data-drawer-target");
        toggleDrawer(target);
      });
    });

    document.querySelectorAll("[data-close-drawer]").forEach((btn) => {
      btn.addEventListener("click", closeDrawers);
    });
  }

  function bindSheets() {
    document.querySelectorAll("[data-sheet-target]").forEach((btn) => {
      btn.addEventListener("click", () => {
        const name = btn.getAttribute("data-sheet-target");
        openSheet(name);
      });
    });

    document.querySelectorAll("[data-close-sheet]").forEach((btn) => {
      btn.addEventListener("click", closeSheets);
    });

    if (sheetOverlay) {
      sheetOverlay.addEventListener("click", (event) => {
        if (event.target === sheetOverlay) {
          closeSheets();
        }
      });
    }
  }

  function bindPalette() {
    document
      .querySelectorAll('[data-toggle="palette"]')
      .forEach((toggleBtn) => {
        toggleBtn.addEventListener("click", togglePalette);
      });

    document.querySelectorAll("[data-close-palette]").forEach((btn) => {
      btn.addEventListener("click", () => {
        if (paletteWindow) {
          paletteWindow.classList.remove("is-active");
        }
      });
    });
  }

  function bindImportFile() {
    const importBtn = document.querySelector(".chip-import");
    const importInput = document.getElementById("importFileInput");
    if (importBtn && importInput) {
      importBtn.addEventListener("click", () => importInput.click());
      importInput.addEventListener("change", () => {
        closeFloating();
      });
    }
  }

  function bindExportTabs() {
    const tabs = document.querySelectorAll("[data-export-tab]");
    const sections = document.querySelectorAll("[data-export-section]");
    if (!tabs.length || !sections.length) return;

    tabs.forEach((tab) => {
      tab.addEventListener("click", () => {
        const target = tab.getAttribute("data-export-tab");
        tabs.forEach((t) => t.classList.toggle("is-active", t === tab));
        sections.forEach((section) => {
          const isMatch =
            section.getAttribute("data-export-section") === target;
          section.classList.toggle("is-active", isMatch);
        });
      });
    });
  }

  function bindAccordions() {
    document.querySelectorAll(".grid-accordion__header").forEach((btn) => {
      btn.addEventListener("click", () => {
        const expanded = btn.getAttribute("aria-expanded") === "true";
        btn.setAttribute("aria-expanded", String(!expanded));
        const content = btn.parentElement?.querySelector(
          ".grid-accordion__content"
        );
        if (content) {
          content.hidden = expanded;
        }
      });
    });
  }

  function openExportWindow() {
    if (!exportWindow) return;
    closeFloating();
    exportWindow.setAttribute("aria-hidden", "false");
  }

  function closeExportWindow() {
    if (!exportWindow) return;
    exportWindow.setAttribute("aria-hidden", "true");
  }

  function bindExportWindow() {
    document
      .querySelectorAll('[data-sheet-target="export"]')
      .forEach((btn) => {
        btn.addEventListener("click", (event) => {
          event.preventDefault();
          openExportWindow();
        });
      });

    const cancelBtn = document.getElementById("exportCancelBtn");
    if (cancelBtn) {
      cancelBtn.addEventListener("click", closeExportWindow);
    }

    if (exportWindow) {
      exportWindow.addEventListener("click", (event) => {
        if (event.target === exportWindow) {
          closeExportWindow();
        }
      });
    }
  }

  function bindMisc() {
    const canvasArea =
      document.querySelector(".workspace") ||
      document.querySelector(".canvas-shell");
    if (canvasArea) {
      canvasArea.addEventListener("click", closeFloating);
    }

    const menuToggle = document.getElementById("menuToggle");
    if (menuToggle) {
      menuToggle.addEventListener("click", () => {
        body.classList.toggle("docks-hidden");
        closeFloating();
      });
    }

    window.addEventListener("keydown", (event) => {
      if (event.key === "Escape") {
        closeFloating();
        closeExportWindow();
      }
    });
  }

  function init() {
    setDeviceMode();
    bindTools();
    bindDrawers();
    bindSheets();
    bindPalette();
    bindImportFile();
    bindExportTabs();
    bindAccordions();
    bindExportWindow();
    bindMisc();
    setTool(state.currentTool);
  }

  init();
  window.addEventListener("resize", setDeviceMode);
  window.addEventListener("orientationchange", setDeviceMode);
})();
